//后台
const router = require("koa-router")();
router.prefix("/admin");
const query = require("../utils/query");
const { setAccessToken,setRefreshToken, secret, } = require("../utils/token");
const jwt = require("jsonwebtoken");
router.post("/login", async (ctx, next) => {
  const { email, password } = ctx.request.body;
  let res = await query(`select * from user where email = '${email}'`);
  let user = res[0];
  if (user) {
    if (user.password === password) {
      ctx.body = {
        code: 200,
        msg: "登录成功",
        result: {
          username: user.username,
          avatar: user.avatar,
          accessToken: setAccessToken(),  //长token
          refreshToken: setRefreshToken(), //短token
        },
      };
    } else {
      ctx.body = {
        code: 201,
        msg: "密码错误",
      };
    }
  } else {
    ctx.body = {
      code: 201,
      msg: "邮箱错误"
    };
  }
});
// 验证长token
router.get("/refreshToken", async (ctx, next) => {
  /*验证长token是否有效，刷新短token
  这里要注意，在刷新短token的时候回也返回新的长token，延续长token，
  这样活跃用户在持续操作过程中不会被迫退出登录。长时间无操作的非活
  跃用户长token过期重新登录
  */
  //验证长token
  const accessToken = ctx.request.headers["pass"];
  jwt.verify(accessToken, secret, (error) => {
    if (error) {
      ctx.body = {
        code: 4009,
        msg: "长token过期",
      };
    } else {
      ctx.body = {
        code: 2000,
        msg: "长token没过期",
        refreshToken: setRefreshToken(),
        accessToken: setAccessToken()
      };
    }
  });
});

const nodemailer = require("../utils/nodemail");
const coder = require("../utils/code");
const serve = require("koa-static");
router.post("/verifycode", async (ctx, next) => {
  const { email } = ctx.request.body;
  let code = coder();
  return nodemailer
    .sendMail(email, code)
    .then(
      (res) =>
        (ctx.body = {
          code: 200,
          result: { code, msg: res },
        })
    )
    .catch(
      (err) =>
        (ctx.body = {
          code: 201,
        })
    );
});

// 添加用户
router.post("/register", async (ctx, next) => {
  const { email, password, username } = ctx.request.body;
  return query(
    `insert into user values(null,'${username}','${email}','${password}',null,null)`
  ).then((res) => {
    ctx.body = {
      code: 200,
      msg: "注册成功",
    };
  });
});
// 修改密码
router.post("/editpass", async (ctx, next) => {
  const { password, email } = ctx.request.body;
  console.log(password, email);
  return query(
    `update user set password = '${password}' where email = '${email}'`
  ).then((res) => {
    ctx.body = {
      code: 200,
      msg: "修改成功",
    };
  });
});

module.exports = router;
